# frozen_string_literal: true

# Provides functionality required to login to WordPress.
module Wpxf::WordPress::Login
  # Build a request body string for a WordPress login request.
  # @param user [String] the username.
  # @param pass [String] the password.
  # @return [String] the request body.
  def wordpress_login_post_body(user, pass)
    redirect = Wpxf::Utility::Text.rand_alpha(10)
    builder = Wpxf::Utility::BodyBuilder.new
    builder.add_field('log', user)
    builder.add_field('pwd', pass)
    builder.add_field('redirect_to', normalize_uri(target_uri, redirect))
    builder.add_field('wp-submit', 'Login')
    builder.create do |body|
      return body
    end
  end

  # @param cookies [String] the session cookies to validate in string form.
  # @return [Boolean] true if a valid WordPress cookie was found.
  def valid_wordpress_cookie?(cookies)
    !(
      cookies =~ /wordpress(?:_sec)?_logged_in_[^=]+=[^;]+;/i ||
      # WordPress 2.0
      cookies =~ /wordpress(?:user|pass)_[^=]+=[^;]+;/i ||
      # WordPress 2.5
      cookies =~ /wordpress_[a-z0-9]+=[^;]+;/i
    ).nil?
  end

  # Log in to WordPress and return the session cookies.
  # @param user [String] the username.
  # @param pass [String] the password.
  # @return [Array, nil] an array of cookies if the login is successful,
  #   otherwise, returns nil.
  def wordpress_login(user, pass)
    res = _execute_wp_login_request(user, pass)

    if res&.cookies
      return res.cookies if valid_wordpress_cookie?(res.cookies.to_s)
    end

    nil
  end

  private

  def _execute_wp_login_request(user, pass)
    res = nil
    scoped_option_change('follow_http_redirection', false) do
      res = execute_post_request(
        url: wordpress_url_login,
        body: wordpress_login_post_body(user, pass)
      )
    end
    res
  end
end
